package com.dhcc.core.api.controller.common;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.dhcc.core.api.auth.IUserAuth;
import com.dhcc.core.api.controller.BaseApiController;
import com.dhcc.core.api.service.ITokenService;
import com.dhcc.core.api.vo.TokenVo;
import com.dhcc.core.api.vo.UserVo;
import com.dhcc.core.framework.result.R;
import com.dhcc.core.framework.util.CommonUtil;
import com.dhcc.core.framework.util.SpringContextHolder;
import com.dhcc.core.modules.system.dao.DeptUserMapper;
import com.dhcc.core.modules.system.entity.User;
import com.dhcc.core.modules.system.service.IUserService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * API登录接口
 * 
 * @ClassName: ApiLoginController
 * @Description: TODO
 * @author: cyf
 * @date: 2018年1月2日 上午10:04:16
 */
@RestController
@RequestMapping("${sys.apiPath}")
@Api("登录接口")
public class ApiLoginController extends BaseApiController {

    @Autowired
    DeptUserMapper deptUserMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private ITokenService tokenService;

    @PostMapping("login")
    @ApiOperation(value = "登录", notes = "登录说明")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "loginName", value = "登录名", required = true),
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "password", value = "密码", required = true) })
    public R login(@RequestParam(required = true) String loginName, @RequestParam(required = true) String password) {

        if (loginName == null || password == null) {
            return R.error("用户名或密码为空！");
        }

        // 验证用户
        IUserAuth userAuth = SpringContextHolder.getBean(IUserAuth.class);
        R r = userAuth.doAuth(loginName, password);
        // 验证失败-推送错误消息-关闭连接
        if (!r.isSuccess()) {
            return r;
        }
        User user = userService.getByLoginName(loginName);

        // 生成token
        TokenVo token = tokenService.getToken(user);
        return R.ok().putObject(token).put("msg", "登录成功").put("currentUser", new UserVo(user));
    }

    /**
     * 刷新token信息
     */
    @PostMapping("refresh_token")
    @ApiOperation(value = "刷新Token", notes = "生成新的Token")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "refreshToken", value = "刷新Token", required = true),
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "deptId", value = "部门id", required = false) })
    public R refreshToken(@RequestParam(required = true) String refreshToken,
            @RequestParam(required = false) Long deptId, HttpServletRequest request) {
        tokenService.verifyToken(refreshToken, true);
        Long userId = tokenService.getUserId(refreshToken);
        User user = userService.selectById(userId);

        // 生成token
        TokenVo token = tokenService.getToken(user);
        return R.ok().putObject(token).put("msg", "登录成功").put("currentUser",
                CommonUtil.isEmpty(deptId) ? new UserVo(user) : new UserVo(user, deptId));
    }

    @PostMapping("logout")
    @ApiOperation("注销token")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "token", value = "访问Token", required = true),
            @ApiImplicitParam(paramType = "form", dataType = "string", name = "refreshToken", value = "刷新Token", required = true) })
    public R logout(@RequestParam(required = true) String token, @RequestParam(required = true) String refreshToken) {
        tokenService.logoutToken(token, refreshToken);
        return R.ok();
    }
}
